package com.huluobo.a2308douyindemo.utils

import android.app.Application
import android.content.Context
import android.os.Handler
import android.os.Looper
import android.widget.Toast
import androidx.databinding.adapters.TextViewBindingAdapter.setText

/**
 *  Created by LC on 2025/10/20.
 */
object MyToast {
    //全局Application上下文,避免内尺寸泄漏
    private lateinit var appContext: Context

    //主线程Handler 确保Toast在主线程中显示
    private val mainHandler = Handler(Looper.getMainLooper())

    //初始化工具类,需要在Application中调用一次
    fun init(application: Application) {
        appContext = application.applicationContext
    }

    //短时间展示Toast
    fun showShort(message: String) {
        checkInit()
        showToast(message, Toast.LENGTH_SHORT)
    }

    //长时间展示Toast
    fun showLong(message: String){
        checkInit()
        showToast(message,Toast.LENGTH_LONG)
    }

    //展示Toast的核心方法
    private fun showToast(message: String, duration: Int) {
        //判断当前Toast的线程是否处于主线程中,是的话,直接展示Toast.非的话通过Handler切换到主线程来进行展示
        if (Looper.myLooper() == Looper.getMainLooper()) {
            try {
                Toast.makeText(appContext, message, duration).show()
            } catch (e: Exception) {
                e.printStackTrace()
            }
        } else {
            //通过Handler切换到主线程来发送Toast
            mainHandler.post {
                try {
                    Toast.makeText(appContext, message, duration).show()
                } catch (e: Exception) {
                    e.printStackTrace()
                }
            }
        }
    }

    //检查是否初始化,未初始化抛出异常
    private fun checkInit() {
        if (!::appContext.isInitialized) {
            throw UninitializedPropertyAccessException("ToastUtils未初始化,请在Application中调用MyToast.init方法")
        }
    }
}